﻿
using Jwt.Share;

using Microsoft.AspNetCore.Components.Authorization;

using System.Net.Http.Json;


namespace Jwt.Client;

public class ApiService
{
    private readonly HttpClient _httpClient;
    private readonly ILocalStorageService _localStorageService;
    private readonly ApiAuthenticationStateProvider _apiAuthenticationStateProvider;
    public ApiService(HttpClient httpClient, ILocalStorageService localStorageService, AuthenticationStateProvider authenticationStateProvider)
    {
        _httpClient = httpClient;
        _localStorageService = localStorageService;
        _apiAuthenticationStateProvider = (ApiAuthenticationStateProvider)authenticationStateProvider;
    }
    public async Task<bool> Login(string userId, string password)
    {
        _apiAuthenticationStateProvider.SetUserStatus();
        var token = await _httpClient.GetFromJsonAsync<string>($"api/token?userid={userId}&password={password}");
        if (string.IsNullOrEmpty(token))
            return false;
        _localStorageService.SetItem("JwtToken", token);
        _apiAuthenticationStateProvider.SetUserStatus();

        return true;
    }
    public void Logout()
    {
        _localStorageService.RemoveItem("JwtToken");
        _apiAuthenticationStateProvider.SetUserStatus();
    }
    public Task<List<WeatherForecast>?> GetWeatherForecasts() => _httpClient.GetFromJsonAsync<List<WeatherForecast>>("api/WeatherForecast");

}
